package org.yang.plugins.resource.handler;

import cn.hutool.json.JSONUtil;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.yang.common.core.result.R;
import org.yang.common.i18n.enums.RI18nEnum;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 自定义: 请求身份验证入口点
 * @author: Islands
 * @create: 2024-06-05 21:25
 */
@Component
public class RequestAuthenticationEntryPoint implements ServerAuthenticationEntryPoint {

    @Override
    public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException ex) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        R<Object> result;
        if(ex instanceof BadCredentialsException){
            //不良凭证
            result = new R<>(false, RI18nEnum.ACCESS_UNAUTHORIZED);
        }else if(ex instanceof InsufficientAuthenticationException){
            //如果是没有携带token
            result = new R<>(false, RI18nEnum.ACCESS_UNAUTHORIZED);
        }else {
            //其他错误
            result = new R<>(false, RI18nEnum.ACCESS_UNAUTHORIZED);
        }
        DataBuffer buffer=response.bufferFactory()
                .wrap(JSONUtil.toJsonStr(result)
                        .getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(buffer));
    }


}
